//
//  UIViewController+WFParams.m
//  WisdomFarm
//
//  Created by sky on 2017/10/30.
//  Copyright © 2017年 sky. All rights reserved.
//

#import "UIViewController+WF.h"
#import "UINavigationController+WFUtils.h"
#import <objc/runtime.h>

@interface UIViewController (WFPrivate)

@property (nonatomic, strong) WFRefreshAdapter *wf_refreshAdapter;


@end

@implementation UIViewController (WF)

+ (void)load {
    Method viewdidload = class_getInstanceMethod([UIViewController class], @selector(viewDidLoad));
    Method wf_viewdidload = class_getInstanceMethod([UIViewController class], @selector(wf_viewDidLoad));
    method_exchangeImplementations(viewdidload, wf_viewdidload);
}

- (void)wf_viewDidLoad {
    [self wf_viewDidLoad];
    [self wf_createBackItemIfNeeded];
}

- (void)wf_createBackItemIfNeeded {
    @weakify(self);
    self.navigationItem.leftBarButtonItem = [self.navigationController wf_backItemWithHandle:^(id sender) {
        @strongify(self);
        if (self.navigationController.viewControllers.count > 1) {
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }];
}

//MARK:- refresh
- (void)setWf_refreshAdapter:(WFRefreshAdapter *)wf_refreshAdapter {
    objc_setAssociatedObject(self, @selector(wf_refreshAdapter), wf_refreshAdapter, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (WFRefreshAdapter *)wf_refreshAdapter {
    return objc_getAssociatedObject(self, @selector(wf_refreshAdapter));
}

- (void)wf_enableRefresh {
    if ([self conformsToProtocol:@protocol(WFRefreshProtocol)]) {
        WFRefreshAdapter *adapter = [[WFRefreshAdapter alloc] init];
        adapter.delegate = (id<WFRefreshProtocol>)self;
        self.wf_refreshAdapter = adapter;
    }
}

- (void)wf_refreshData {
    if ([self conformsToProtocol:@protocol(WFRefreshProtocol)]) {
        id<WFRefreshProtocol> delegate = (id<WFRefreshProtocol>)self;
        @weakify(delegate);
        [delegate refreshDataWithCompletion:^(BOOL hasNext, NSError *error) {
            @strongify(delegate);
            [delegate.mainScrollView.mj_header endRefreshing];
        }];
    }
}

@end

@implementation UIViewController (WFParams)

+ (instancetype)controllerWithParams:(NSDictionary *)params {
    UIViewController *controller = [[[self class] alloc] init];
    for (NSString *key in params) {
        if ([controller respondsToSelector:NSSelectorFromString(key)]) {
            [controller setValue:params[key] forKey:key];
        }
    }
    return controller;
}

@end
